package com.ai.txyun.deepseek;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DeepSeekDemo {
    public static void main(String[] args) {
        String apiKey = "sk-密钥";
        String baseUrl = "https://api.deepseek.com/v1/chat/completions";
        String model = "deepseek-chat";
        String systemMessage = "You are a helpful assistant";
        String userMessage = "张崇炼在族谱中属于哪个区域的后代";

        try {
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", model);
            
            List<Map<String, String>> messages = new ArrayList<>();
            Map<String, String> systemMsg = new HashMap<>();
            systemMsg.put("role", "system");
            systemMsg.put("content", systemMessage);
            messages.add(systemMsg);
            
            Map<String, String> userMsg = new HashMap<>();
            userMsg.put("role", "user");
            userMsg.put("content", userMessage);
            messages.add(userMsg);
            
            requestBody.put("messages", messages);
            requestBody.put("stream", false);
            requestBody.put("temperature", 0.6);
            requestBody.put("max_tokens", 1024);

            // 转换为 JSON 字符串
            String requestJson = toJson(requestBody);

            // 发送 HTTP 请求
            URL url = new URL(baseUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", "Bearer " + apiKey);
            connection.setDoOutput(true);

            // 写入请求体
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = requestJson.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 读取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    System.out.println(parseResponse(response.toString()));
                }
            } else {
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    System.err.println("HTTP Error: " + responseCode);
                    System.err.println("Error Response: " + response.toString());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 简易 JSON 生成器（实际生产环境建议使用 Jackson 或 Gson）
    private static String toJson(Map<String, Object> map) {
        StringBuilder json = new StringBuilder("{");
        boolean first = true;
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (!first) {
                json.append(",");
            }
            json.append("\"").append(entry.getKey()).append("\":");
            
            Object value = entry.getValue();
            if (value instanceof String) {
                json.append("\"").append(value).append("\"");
            } else if (value instanceof List) {
                json.append(toJsonArray((List<?>) value));
            } else if (value instanceof Map) {
                json.append(toJson((Map<String, Object>) value));
            } else {
                json.append(value);
            }
            first = false;
        }
        json.append("}");
        return json.toString();
    }

    private static String toJsonArray(List<?> list) {
        StringBuilder jsonArray = new StringBuilder("[");
        boolean first = true;
        for (Object item : list) {
            if (!first) {
                jsonArray.append(",");
            }
            if (item instanceof String) {
                jsonArray.append("\"").append(item).append("\"");
            } else if (item instanceof Map) {
                jsonArray.append(toJson((Map<String, Object>) item));
            } else {
                jsonArray.append(item);
            }
            first = false;
        }
        jsonArray.append("]");
        return jsonArray.toString();
    }

    // 简易响应解析（实际生产环境建议使用 JSON 解析库）
    private static String parseResponse(String response) {
        int contentStart = response.indexOf("\"content\":\"") + 11;
        if (contentStart < 11) return "Failed to parse response";
        
        int contentEnd = response.indexOf("\"", contentStart);
        if (contentEnd == -1) return "Failed to parse response";
        
        return response.substring(contentStart, contentEnd)
                .replace("\\n", "\n")
                .replace("\\\"", "\"");
    }
}